import 'dart:convert';
import 'dart:typed_data';

import 'package:pointycastle/export.dart';
import 'package:asn1lib/asn1lib.dart';

/// RSA加密工具类
class RSAUtils {
  /// RSA公钥
  static const String publicKeyString =
      'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGTKvALj0gUYDg2bMTRFLjRCFkg2q+3Z/ziyA5VXBCpLiMRhu1rixa2g57tVkg5zKx3zIJMipnusMVSGr07iuLHJTkIw9WdIDREWDoToQxbj4jggZNTt7ZWOcQpFgNT8aZ5Ul+0s8fUmlFdwEX/3c5H2r+echmHp1cKD/yDvNZ5wIDAQAB';

  /// 解析RSA公钥
  static RSAPublicKey _parsePublicKey(String key) {
    final keyBytes = base64Decode(key);
    final asn1Parser = ASN1Parser(keyBytes);
    final topLevelSeq = asn1Parser.nextObject() as ASN1Sequence;
    final publicKeyBitString = topLevelSeq.elements[1];

    final publicKeyAsn = ASN1Parser(publicKeyBitString.contentBytes());
    final publicKeySeq = publicKeyAsn.nextObject() as ASN1Sequence;

    final modulus = publicKeySeq.elements[0] as ASN1Integer;
    final exponent = publicKeySeq.elements[1] as ASN1Integer;

    final rsaPublicKey = RSAPublicKey(
      modulus.valueAsBigInteger,
      exponent.valueAsBigInteger,
    );

    return rsaPublicKey;
  }

  /// RSA加密
  static String encrypt(String plainText) {
    try {
      final publicKey = _parsePublicKey(publicKeyString);
      final encryptor = PKCS1Encoding(RSAEngine());
      encryptor.init(true, PublicKeyParameter<RSAPublicKey>(publicKey));

      final plainBytes = utf8.encode(plainText);
      final encrypted = encryptor.process(Uint8List.fromList(plainBytes));
      return base64Encode(encrypted);
    } catch (e) {
      throw Exception('RSA加密失败: $e');
    }
  }

  /// 加密手机号
  static String encryptPhone(String phone) {
    return encrypt(phone);
  }

  /// 加密密码
  static String encryptPassword(String password) {
    return encrypt(password);
  }
}
